<template>
  <el-dialog
    class="role-privilege-dialog"
    :visible.sync="visible"
    title="管理角色权限"
    width="600px"
    :close-on-click-modal="false"
  >
    <el-tree
      v-if="visible"
      v-loading="isLoading"
      ref="privilegeTree"
      :data="privilegeList"
      :props="{ label: 'name', children: 'children' }"
      node-key="id"
      check-on-click-node
      show-checkbox
      check-strictly
      :expand-on-click-node="false"
      :default-checked-keys="rolePrivilegeKeys"
      :default-expanded-keys="rolePrivilegeKeys"
    >
      <div slot-scope="{ node }">
        <span>{{ node.label }}</span>
        <div v-if="!node.isLeaf" class="tree-node-buttons">
          <el-button type="text" size="mini" @click.native.stop="handleSelectAll(node)">
            全选/取消
          </el-button>
        </div>
      </div>
    </el-tree>
    <div slot="footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="$wait.is('account.role.getRolePrivileges')"
        >保 存</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      visible: false,
      rolePrivileges: [],
      privilegeList: [],
      currentRole: {},
    };
  },

  computed: {
    // 返回角色的id
    rolePrivilegeKeys() {
      return this.rolePrivileges;
    },
    // 定义loading的值
    isLoading() {
      return this.$wait.is('account.role.getRolePrivileges') || this.$wait.is('account.privilege.getPrivilegeList');
    },
  },

  methods: {
    show(model) {
      this.visible = true;

      this.currentRole = { ...model };

      this.getPrivilegeList();
      this.fetchRolePrivileges();
    },

    close() {
      this.visible = false;
    },

    /**
     * 保存角色用户权限方法
     */
    async handleSubmit() {
      const privilegeKeys = this.$refs.privilegeTree.getCheckedNodes().map(item => item.id);
      const params = {
        roleId: this.currentRole.id,
        resourceIds: privilegeKeys.join(','),
      };

      await this.$api.account.role.editRolePrivileges(params);
      this.$message.success('保存成功');
      this.close();
      this.$emit('submit');
    },
    /**
     * x选中全部节点
     * @param node 节点值
     */
    handleSelectAll(node) {
      const getAllNodes = nodeItem => {
        const result = [nodeItem];
        if (nodeItem.childNodes) {
          // 遍历节点下的子节点，并存入result中
          for (const child of nodeItem.childNodes) {
            result.push(...getAllNodes(child));
          }
        }
        return result;
      };
      const { privilegeTree } = this.$refs;
      const allNodes = getAllNodes(node);
      const allChecked = allNodes.every(item => item.checked);
      // 所有节点都设置选中
      allNodes.forEach(nodeItem => {
        privilegeTree.setChecked(nodeItem.key, !allChecked);
      });
    },
    /**
     * 初始化设置权限勾选
     */
    async fetchRolePrivileges() {
      if (this.currentRole.id) {
        // 调用接口
        const { data } = await this.$api.account.role.getRolePrivileges({
          roleId: this.currentRole.id,
        });

        // 更新权限值
        this.rolePrivileges = data || [];
      }
    },

    async getPrivilegeList() {
      const { data } = await this.$api.account.privilege.getPrivilegeList();

      this.privilegeList = data;
    },
  },
};
</script>

<style lang="scss" scoped>
.role-privilege-dialog {
  .tree-node-buttons {
    display: inline-block;
    margin-left: 12px;
  }
  span.el-checkbox__input.is-indeterminate .el-checkbox__inner {
    background-color: #2f71f2 !important;
    border-color: #2f71f2 !important;
  }
}
</style>
